/*
 * @lc app=leetcode.cn id=993 lang=typescript
 *
 * [993] 二叉树的堂兄弟节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function isCousins(root: TreeNode, x: number, y: number): boolean {
    let record = {
        x: [] as any as [TreeNode | undefined, number | undefined],
        y: [] as any as [TreeNode | undefined, number | undefined],
    };
    const tra = (
        root: TreeNode | null,
        deep = 0,
        father: null | TreeNode = null
    ) => {
        if (!root) return;
        if (root.val === x) {
            record.x = [father!, deep];
        }
        if (root.val === y) {
            record.y = [father!, deep];
        }
        /* @ts-ignore */
        if (record.x.length === 0 || record.y.length === 0) {
            tra(root.left, deep + 1, root);
            tra(root.right, deep + 1, root);
        }
    };
    tra(root, 0, null);
    return record.x[1] === record.y[1] && record.x[0] !== record.y[0];
}
// @lc code=end
